package cn.dkk.structure_design.proxy.dynamic_proxy.CGLib;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author dkk
 * @date 2022/7/10
 * @desc cglib代理工厂
 */
public class ProxyFactory implements MethodInterceptor {

    private final Target target=new Target();

    public Target getProxy(){
        Enhancer enhancer = new Enhancer();// 代理器,类似于jdk的Proxy
        enhancer.setSuperclass(Target.class);// 设置代理的父类字节码
        enhancer.setCallback(this);// 设置回调函数对象,本类实现MethodInterceptor重写intercept即可
        return (Target) enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        // MethodProxy是方法签名的对象,可以通过签名来判断调用的方法
        System.out.println("代理逻辑");
        return method.invoke(target,objects);
    }
}
